package com.wyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.wyy.beans.Resource;
import com.wyy.beans.ResourceRole;
import com.wyy.common.Result;
import com.wyy.dao.ResourceDao;
import com.wyy.dao.ResourceRoleDao;
import com.wyy.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceDao resourceDao;

    @Autowired
    private ResourceRoleDao resourceRoleDao;

    @Override
    public Result<Resource> addResource(Resource resource) {
        QueryWrapper<Resource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "resource_name", resource.getResourceName());
        Resource newResource = resourceDao.selectOne(queryWrapper);
        if (newResource != null) {
            return new Result<>(Result.ResultStatus.Failed.code, "重复");
        }

        int aff = resourceDao.insert(resource);
        if (resource.getRoles() != null) {
            resource.getRoles()
                    .forEach(role -> resourceRoleDao.insert(
                            new ResourceRole(resource.getReId(), role.getRid())));
        }
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Result<Resource> updateResource(Resource resource) {
        Resource newResource = getResourceById(resource.getReId());
        if (newResource == null) {
            return new Result<>(Result.ResultStatus.Failed.code, "无此资源");
        }

        int aff = resourceDao.updateById(resource);
        if (resource.getRoles() != null) {
            resourceRoleDao.deleteRoleResourceByResourceId(resource.getReId());
            resource.getRoles()
                    .forEach(role -> resourceRoleDao.insert(
                            new ResourceRole(resource.getReId(), role.getRid())));
        }
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Result<Resource> deleteResourceById(long id) {
        resourceDao.deleteById(id);
        resourceRoleDao.deleteRoleResourceByResourceId(id);
        return new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Resource getResourceById(long id) {
        return resourceDao.selectById(id);
    }

    @Override
    public List<Resource> getResourcesByRoleId(long roleId) {
        return Optional.ofNullable(resourceDao.getResourcesByRoleId(roleId)).orElse(Collections.emptyList());
    }
}
